package net.zhuike.novel.app.ui.fragment;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.umeng.analytics.MobclickAgent;

import net.zhuike.novel.app.R;
import net.zhuike.novel.app.bean.CategoryList;
import net.zhuike.novel.app.bean.RankingList;
import net.zhuike.novel.app.bean.Recommend;
import net.zhuike.novel.app.bean.TabEntity;
import net.zhuike.novel.app.bean.TabModel;
import net.zhuike.novel.app.bean.TabModelResult;
import net.zhuike.novel.app.common.OnRvItemClickListener;
import net.zhuike.novel.app.service.BookShelfService;
import net.zhuike.novel.app.service.BookStoreService;
import net.zhuike.novel.app.ui.activity.SearchActivity;
import net.zhuike.novel.app.ui.activity.SubRankActivity;
import net.zhuike.novel.app.ui.adapter.TopCategoryListAdapter;
import net.zhuike.novel.app.ui.adapter.TopRankAdapter;
import net.zhuike.novel.app.ui.base.BaseFragment;
import net.zhuike.novel.app.ui.base.Constant;
import net.zhuike.novel.app.ui.utils.SharedPreferencesUtil;
import net.zhuike.novel.app.ui.view.SupportGridItemDecoration;
import net.zhuike.novel.app.ui.view.UeDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import framework.common.views.InnerGridView;
import framework.common.views.InnerListView;
import framework.common.zanetwork.core.ResponseCallback;
import okhttp3.Response;

/**
 * Created by wq on 2017/6/10.
 * 书城
 */
public class BookStoreFragment extends BaseFragment implements View.OnClickListener {
    @Bind(R.id.book_stor_ranking)
    TextView bookStorRankingTv;
    @Bind(R.id.book_stor_classification)
    TextView bookStorClassificationTv;
    @Bind(R.id.rankingLin)
    LinearLayout rankingLin;
    @Bind(R.id.classificationLin)
    LinearLayout classificationLin;
    @Bind(R.id.classifyImg)
    ImageView classifyImg;
    @Bind(R.id.rankingImg)
    ImageView rankingImg;
    @Bind(R.id.goSearchLayout)
    LinearLayout goSearchLayout;
    @Bind(R.id.rankingLinBg)
    LinearLayout rankingLinBg;
    @Bind(R.id.classificationBg)
    LinearLayout classificationBg;
    @Bind(R.id.tl_ranking)
    CommonTabLayout tlRanking;
    @Bind(R.id.tl_classification)
    CommonTabLayout tlClassification;
    @Bind(R.id.elvMale)
    ExpandableListView elvMale;
    @Bind(R.id.rvMaleCategory)
    InnerGridView mRvMaleCategory;
    private Context context;
    private int select = 0;
    private List<TabModel> maleGroups = new ArrayList<>();
    private TopRankAdapter maleAdapter;
    private List<List<TabModel>> mMaleCategoryList = new ArrayList<>();
    List<TabModel>ranktabList=new ArrayList<>();
    List<TabModel>tabList=new ArrayList<>();

    private TopCategoryListAdapter mMaleCategoryListAdapter;
    private List<TabModel> mMaleCategoryLists = new ArrayList<>();
    private int[] mIconUnselectIds = {
            R.mipmap.ic_boy_tag, R.mipmap.ic_gir_tag,
            R.mipmap.ic_other_tag};
    private int[] mIconSelectIds = {
            R.mipmap.ic_boy_tag, R.mipmap.ic_gir_tag,
            R.mipmap.ic_other_tag};

    private ArrayList<CustomTabEntity> mRankingTabEntities = new ArrayList<>();
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();

    private int showType=0;
    @Override
    public int getLayoutResId() {
        return R.layout.fragment_store;
    }

    @Override
    public void initDatas() {

    }

    @Override
    public void configViews() {
        context = getActivity();
        rankingLin.setOnClickListener(this);
        classificationLin.setOnClickListener(this);
        goSearchLayout.setOnClickListener(this);
        mRvMaleCategory.setOnItemClickListener(clickItem);
        tlRanking.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                TabModel  model=ranktabList.get(position);
                getCategoryList(model.getId());
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        tlClassification.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                TabModel  model=tabList.get(position);

            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        UeDialog.showprogressDialog(context,"","加载中",false);
        getTabs();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rankingLin:
                select = 0;
                bookStorRankingTv.setTextColor(Color.parseColor("#ffffff"));
                bookStorClassificationTv.setTextColor(Color.parseColor("#1089DC"));
                rankingImg.setImageResource(R.mipmap.ic_ranking_hover);
                rankingLin.setBackgroundResource(R.drawable.shape_bg_left_normal);
                classifyImg.setImageResource(R.mipmap.ic_classify_normal);
                classificationLin.setBackgroundResource(R.drawable.shape_bg_right_normal);
                rankingLinBg.setVisibility(View.VISIBLE);
                classificationBg.setVisibility(View.GONE);
                getCategoryList("101");
                break;
            case R.id.classificationLin:
                select = 1;
                rankingImg.setImageResource(R.mipmap.ic_ranking_normal);
                classifyImg.setImageResource(R.mipmap.ic_classify_hover);
                bookStorRankingTv.setTextColor(Color.parseColor("#1089DC"));
                bookStorClassificationTv.setTextColor(Color.parseColor("#ffffff"));
                rankingLin.setBackgroundResource(R.drawable.shape_bg_left);
                classificationLin.setBackgroundResource(R.drawable.shape_bg_right);
                rankingLinBg.setVisibility(View.GONE);
                classificationBg.setVisibility(View.VISIBLE);
                getCategoryList("106");
                break;
            case R.id.goSearchLayout:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
        }
    }
    public void getTabs() {

        String topCategoryId= SharedPreferencesUtil.getInstance().getString(Constant.TopCategoryId);
        BookStoreService.getTab(context, topCategoryId, new ResponseCallback<TabModelResult>() {
            @Override
            public void onSuccess(TabModelResult advertisesModels) {
                 if(advertisesModels!=null){
                     UeDialog.hideProgress();
                     ranktabList.clear();
                     tabList.clear();
                     for(int i=0;i<advertisesModels.getSubCategories().size();i++){
                         TabModel  model=advertisesModels.getSubCategories().get(i);
                         if(model.getId().equals("11")){
                             ranktabList.addAll(model.getSubCategories());
                             for (int j = 0; j <ranktabList.size(); j++) {
                                 mRankingTabEntities.add(new TabEntity(ranktabList.get(j).getName(), mIconSelectIds[j], mIconUnselectIds[j]));
                             }
                             getCategoryList("101");
                         }else
                         if(model.getId().equals("12")){
                             for (int j = 0; j <model.getSubCategories().size(); j++) {
                                 mTabEntities.add(new TabEntity(model.getSubCategories().get(j).getName(), mIconSelectIds[j], mIconUnselectIds[j]));
                             }

                         }
                     }

                     tlRanking.setTabData(mRankingTabEntities);
                    tlClassification.setTabData(mTabEntities);

                 }

            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                UeDialog.hideProgress();
            }
        });
    }
    class ClickListener implements OnRvItemClickListener<TabModel> {

        @Override
        public void onItemClick(View view, int position, TabModel data) {
            String allId = null;
            if (allId == null) {
                allId = data.getId();
            }
            SubRankActivity.startActivity(mContext, allId, data.getName());
        }
    }
    public void getCategoryList(String id) {
        String topCategoryId= SharedPreferencesUtil.getInstance().getString(Constant.TopCategoryId);
        BookStoreService.getTab(context, topCategoryId, new ResponseCallback<TabModelResult>() {
            @Override
            public void onSuccess(TabModelResult advertisesModels) {
                if(advertisesModels!=null){
                    tabList.clear();
                    for(int i=0;i<advertisesModels.getSubCategories().size();i++){
                        TabModel model=advertisesModels.getSubCategories().get(i);
                        if(select==0) {
                            if (model.getId().equals("11")) {
                                if (model.getSubCategories() != null) ;
                                for (int j = 0; j < model.getSubCategories().size(); j++) {
                                    TabModel models = model.getSubCategories().get(j);
                                    if (models.getId().equals(id)) {
                                        if (models.getSubCategories() != null) {
                                            tabList.addAll(models.getSubCategories());
                                        }
                                    }
                                }

                            }
                        }else{
                            if (model.getId().equals("12")) {
                                if (model.getSubCategories() != null) ;
                                for (int j = 0; j < model.getSubCategories().size(); j++) {
                                    TabModel models = model.getSubCategories().get(j);
                                    if (models.getId().equals(id)) {
                                        if (models.getSubCategories() != null) {
                                            tabList.addAll(models.getSubCategories());
                                        }
                                    }
                                }

                            }
                        }
                    }
                    if(select==0){
                        showRankList(tabList);
                    }else{
                        showCategoryList(tabList);
                    }
                }

            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }
    public void showCategoryList(List<TabModel>list) {
        mMaleCategoryLists.clear();
        mMaleCategoryLists.addAll(list);
        if(mMaleCategoryListAdapter==null){
            mMaleCategoryListAdapter = new TopCategoryListAdapter(mContext, mMaleCategoryLists, new ClickListeners(Constant.Gender.MALE));
            mRvMaleCategory.setAdapter(mMaleCategoryListAdapter);
        }else {
            mMaleCategoryListAdapter.data = mMaleCategoryLists;
            mMaleCategoryListAdapter.notifyDataSetChanged();
        }
    }
    public void showRankList(List<TabModel>list) {
        mMaleCategoryList.clear();
        maleGroups.clear();
        updateMale(list);
    }
    private void updateMale(List<TabModel>list) {
        List<TabModel> lists = list;
        List<TabModel> collapse = new ArrayList<>();
        for (TabModel bean : lists) {
            if (bean.isCollapse()) { // 折叠
                collapse.add(bean);
            } else {
                maleGroups.add(bean);
                mMaleCategoryList.add(new ArrayList<TabModel>());
            }
        }
        maleAdapter = new TopRankAdapter(getActivity(), maleGroups, mMaleCategoryList);
        maleAdapter.setItemClickListener(new ClickListener());
        elvMale.setAdapter(maleAdapter);
    }
    AdapterView.OnItemClickListener clickItem = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // TODO Auto-generated method stub

            TabModel data=mMaleCategoryLists.get(arg2);
            SubRankActivity.startActivity(mContext,data.getId(),data.getName());
        }

    };
    class ClickListeners implements OnRvItemClickListener<TabModel> {

        private String gender;

        public ClickListeners(@Constant.Gender String gender) {
            this.gender = gender;
        }

        @Override
        public void onItemClick(View view, int position, TabModel data) {
            SubRankActivity.startActivity(mContext,data.getName(),data.getId());
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("书城");
        MobclickAgent.onResume(context);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("书城");
        MobclickAgent.onPause(context);
    }
}
